package com.demoworld.controllers;

import com.demoworld.ContextHolder;
import com.demoworld.ContextHolder1;
import com.demoworld.ContextHolder2;
import com.demoworld.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/")
public class IndexController {
    @Autowired
    private ContextHolder contextHolder;

    @Autowired
    private ContextHolder1 contextHolder1;

    @Autowired
    private ContextHolder2 contextHolder2;

    @RequestMapping("1")
    public String get1() {
        IndexController indexController = SpringContextUtil.getBean(IndexController.class);
        //因为controller实例默认是单例的， 所以通过上下文获取的 index Controller实例和当前this 实例的hashcode 应该是一样的。所以相减等于0
        return String.valueOf(this.hashCode() - indexController.hashCode());
    }

    @RequestMapping("2")
    public String get2(HttpServletRequest request) {
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        IndexController indexController = ctx.getBean(IndexController.class);
        //这种方法获取的不是当前的controller 实例， 待确认为啥
        return String.valueOf(this.hashCode() - indexController.hashCode()) + " 这个需要确认获取的实例不是当前运行的controller实例";
    }

    @RequestMapping("3")
    public String get3() {
        IndexController indexController = contextHolder.getApplicationContext().getBean(IndexController.class);
        //因为controller实例默认是单例的， 所以通过上下文获取的 index Controller实例和当前this 实例的hashcode 应该是一样的。所以相减等于0
        return String.valueOf(this.hashCode() - indexController.hashCode());
    }

    @RequestMapping("4")
    public String get4() {
        IndexController indexController = contextHolder1.getApplicationContext().getBean(IndexController.class);
        //因为controller实例默认是单例的， 所以通过上下文获取的 index Controller实例和当前this 实例的hashcode 应该是一样的。所以相减等于0
        return String.valueOf(this.hashCode() - indexController.hashCode());
    }

    @RequestMapping("5")
    public String get5() {
        IndexController indexController = contextHolder2.getCtx().getBean(IndexController.class);
        //因为controller实例默认是单例的， 所以通过上下文获取的 index Controller实例和当前this 实例的hashcode 应该是一样的。所以相减等于0
        return String.valueOf(this.hashCode() - indexController.hashCode());
    }
}
